//
//  CYBankcardBandTableViewController.m
//  CreditAddressBook
//
//  Created by Mosu&Cuu on 16/2/19.
//  Copyright © 2016年 Lee. All rights reserved.
//

#import "CYBankcardBandTableViewController.h"
#import "CYUser.h"
#import "CYLoginHttpTool.h"
#import "CYHttpTool.h"
#import "CYJsonInfo.h"
#import "NSObject+MJKeyValue.h"
#import "MBProgressHUD+MJ.h"
#import "DSNavigationBar.h"
#import "CYDES3Util.h"
#import "CYCommonReleaseTVC.h"
#import "AddressView.h"
#import "UIAlertView+Block.h"
#import "DCPaymentView.h"
#import "CYTool.h"
#import "CYJumpsTool.h"

@interface CYBankcardBandTableViewController ()<UIPickerViewDelegate,UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITextField *banktext;
@property (weak, nonatomic) IBOutlet UILabel *phoneLabel;
@property (weak, nonatomic) IBOutlet UITextField *cardtext;
@property (weak, nonatomic) IBOutlet UITextField *provincetext;
@property (weak, nonatomic) IBOutlet UITextField *fenhangtext;
@property (weak, nonatomic) IBOutlet UITextField *nameLab;
@property (weak, nonatomic) IBOutlet UITableViewCell *chaxunCell;
@property (nonatomic, strong) UIToolbar *toolBar;
@property (nonatomic, strong) UIPickerView *picker;
@property (nonatomic, strong) NSArray *pickdata;

//地区选择器
@property (nonatomic, strong) UIToolbar *addresstoolBar;
@property (nonatomic, strong) UIPickerView *addresspicker;
@property (nonatomic, strong) AddressView *selectaddressView;

@property (nonatomic, strong) NSString *provincestr;
@property (nonatomic, strong) NSString *citystr;
@property (nonatomic, strong) NSString *areastr;


@property (nonatomic,strong) UIView * writeView;
@property (nonatomic,strong) UIView * shituview;
@property (nonatomic,strong) NSString * weixinname;
@property (nonatomic, strong) NSString *namestr;
@property (nonatomic, strong) NSString *idcardstr;
@end

@implementation CYBankcardBandTableViewController



- (void)viewDidLoad {
    [super viewDidLoad];
    self.title  = @"银行卡改绑";
    CYUser *user = [CYLoginHttpTool userData].user;
     _phoneLabel.text = user.phone;
//    _nameLab.text = user.name;
    UIButton*rightButton = [[UIButton alloc]initWithFrame:CGRectMake(0,0,50,30)];
    rightButton.titleLabel.textColor = [UIColor blackColor];
    [rightButton addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside];
    [rightButton setTitle:@"绑定" forState:UIControlStateNormal];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithCustomView:rightButton];
     self.navigationItem.rightBarButtonItem= rightItem;
    
     _cardtext.delegate = self;
     _fenhangtext.delegate = self;
     
     _picker = [[UIPickerView alloc] initWithFrame:CGRectMake(0, self.view.height/1.5,self.view.width,self.view.height/3 )];
     //    指定Delegate
     _picker.delegate=self;
     NSArray *dataArray = [[NSArray alloc]initWithObjects:@"中国工商银行",@"中国农业银行",@"中国银行",@"中国建设银行",@"交通银行",@"中国建设银行",@"交通银行",@"招商银行",@"兴业银行",@"中国民生银行",@"广东发展银行",@"深圳发展银行",@"上海浦东发展银行",@"华夏银行",@"富滇银行",@"中国光大银行",@"中信银行",@"平安银行",@"东亚银行",@"上海银行",@"中国邮政银行",@"南京银行",@"上海农商银行",@"渤海银行",@"成都银行",@"北京银行",nil];
     _pickdata=dataArray;
     _picker.showsSelectionIndicator=YES;
     _banktext.inputView = self.picker;
     _banktext.inputAccessoryView = self.toolBar;
     
     _addresspicker =[[UIPickerView alloc] initWithFrame:CGRectMake(0, self.view.height/1.5,self.view.width,self.view.height/3 )];
     _addresspicker.delegate = self;
     self.selectaddressView = [[AddressView alloc] init];
     self.provincetext.inputView = self.selectaddressView;
     self.provincetext.inputAccessoryView = self.addresstoolBar;

}
//电话号码修改
- (IBAction)PonexiugaiOnclicked:(id)sender {
     UIView *bgView = [[UIView alloc] initWithFrame:self.view.frame];
     bgView.backgroundColor = [UIColor grayColor];
     bgView.alpha = 0.8;
     self.writeView = bgView;
     self.writeView.hidden = NO;
     [[UIApplication sharedApplication].keyWindow addSubview:_writeView];
     
     _shituview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 260, 290)];
     _shituview.layer.cornerRadius = 5;
     _shituview.layer.masksToBounds = YES;
     _shituview.center = self.view.center;
     _shituview.backgroundColor = [UIColor whiteColor];
     [[UIApplication sharedApplication].keyWindow addSubview:_shituview];
     [[UIApplication sharedApplication].keyWindow bringSubviewToFront:_shituview];
     UILabel * tishiLabel = [[UILabel alloc] init];
     tishiLabel.frame = CGRectMake(_shituview.frame.size.width /2 - 23, 5, 40, 20);
     tishiLabel.text = @"提示";
     tishiLabel.textAlignment = NSTextAlignmentCenter;
     tishiLabel.font = [UIFont systemFontOfSize:16.0];
     [_shituview addSubview:tishiLabel];
     
     UILabel * yonghuLB = [[UILabel alloc] init];
     yonghuLB.frame = CGRectMake(10, 30, _shituview.frame.size.width - 20, 15);
     yonghuLB.text = @"尊敬的用户您好,修改手机号码成功后,";
     yonghuLB.numberOfLines = 0;
     yonghuLB.font = [UIFont systemFontOfSize:14.0];
     UILabel * xuyaoLB = [[UILabel alloc] init];
     xuyaoLB.frame = CGRectMake(10, 50, _shituview.frame.size.width - 20, 15);
     xuyaoLB.text = @"需要重新完成运营商认证,步骤如下:";
     xuyaoLB.numberOfLines = 0;
     xuyaoLB.font = [UIFont systemFontOfSize:14.0];
     [_shituview addSubview:yonghuLB];
     [_shituview addSubview:xuyaoLB];
     UILabel * addLabel = [[UILabel alloc] init];
     addLabel.frame = CGRectMake(10, 75, _shituview.frame.size.width - 20, 15);
     addLabel.text = @"1.添加微信公众号：";
     addLabel.font = [UIFont systemFontOfSize:14.0];
     [_shituview addSubview:addLabel];
     UILabel * tianxiaLb = [[UILabel alloc] init];
     tianxiaLb.frame = CGRectMake(10, 95, 120, 15);
     tianxiaLb.text = @"天下无赖诚信联盟";
     
     _weixinname = tianxiaLb.text;
     tianxiaLb.font = [UIFont systemFontOfSize:14.0];
     [_shituview addSubview:tianxiaLb];
     
     UIButton * fuzhiBtn = [[UIButton alloc] initWithFrame:CGRectMake(tianxiaLb.frame.size.width + 50, 90, 40, 25)];
     fuzhiBtn.backgroundColor = [UIColor grayColor];
     fuzhiBtn.layer.cornerRadius = 3;
     fuzhiBtn.layer.masksToBounds = YES;
     [fuzhiBtn setTitle:@"复制" forState:UIControlStateNormal];
     [fuzhiBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
     fuzhiBtn.titleLabel.font = [UIFont systemFontOfSize:16];
     [fuzhiBtn addTarget:self action:@selector(fuzhiDClicked) forControlEvents:UIControlEventTouchUpInside];
     [_shituview addSubview:fuzhiBtn];
     
     UIView * lineView = [[UIView alloc] initWithFrame:CGRectMake(10, 120, _shituview.frame.size.width - 20, 1)];
     lineView.backgroundColor = [UIColor grayColor];
     [_shituview addSubview:lineView];
     
     UILabel * twoLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 130, _shituview.frame.size.width - 20, 15)];
     twoLabel.text = @"2.给“天下无赖诚信联盟”留言";
     twoLabel.font = [UIFont systemFontOfSize:14.0];
     [_shituview addSubview:twoLabel];
     
     UILabel * liuyanLb = [[UILabel alloc] initWithFrame:CGRectMake(10, 150, _shituview.frame.size.width - 20, 15)];
     liuyanLb.text = @"留言示例：";
     liuyanLb.font = [UIFont systemFontOfSize:14.0];
     [_shituview addSubview:liuyanLb];
     UILabel * shoujiLb = [[UILabel alloc] initWithFrame:CGRectMake(10, 175, _shituview.frame.size.width - 20, 15)];
     shoujiLb.text = @"3.手机号码更换申请";
     shoujiLb.font = [UIFont systemFontOfSize:14.0];
     [_shituview addSubview:shoujiLb];
     
     UILabel * jiuLb = [[UILabel alloc] initWithFrame:CGRectMake(10, 195, _shituview.frame.size.width - 20, 15)];
     jiuLb.text = @"旧号码：13****xxx";
     jiuLb.font = [UIFont systemFontOfSize:14.0];
     [_shituview addSubview:jiuLb];
     
     UILabel * xinLb = [[UILabel alloc] initWithFrame:CGRectMake(10, 215, _shituview.frame.size.width - 20, 15)];
     xinLb.text = @"新号码：15****xxx";
     xinLb.font = [UIFont systemFontOfSize:14.0];
     [_shituview addSubview:xinLb];
     
     UIView * lineTwoView = [[UIView alloc] initWithFrame:CGRectMake(10, 240, _shituview.frame.size.width - 20, 1.0f)];
     lineTwoView.backgroundColor = [UIColor grayColor];
     [_shituview addSubview:lineTwoView];
     
     UIButton * quxiaoBtn = [[UIButton alloc] initWithFrame:CGRectMake(20, 250, _shituview.frame.size.width - 40, 30)];
     quxiaoBtn.backgroundColor = [UIColor colorWithRed:111/255.0 green:185/255.0 blue:87/255.0 alpha:1];
     quxiaoBtn.layer.cornerRadius = 3;
     quxiaoBtn.layer.masksToBounds = YES;
     [quxiaoBtn setTitle:@"取消" forState:UIControlStateNormal];
     [quxiaoBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
     [quxiaoBtn addTarget:self action:@selector(quxiaoBtnOclicked) forControlEvents:UIControlEventTouchUpInside];
     [_shituview addSubview:quxiaoBtn];
     
}

- (void)fuzhiDClicked {
     UIPasteboard *pab = [UIPasteboard generalPasteboard];
     [pab setString:_weixinname];
     if (pab == nil) {
          [MBProgressHUD showError:@"复制失败"];
          
     }else
     {
          [MBProgressHUD showSuccess:@"已复制"];
          
     }

}

- (void)quxiaoBtnOclicked {
     _writeView.hidden = YES;
     _shituview.hidden = YES;
}
//开户行查询按钮点击
- (IBAction)chaxunOnclicked:(id)sender {
     
     [_chaxunCell.contentView addSubview:sender];
     _cardtext.delegate = self;
     _fenhangtext.delegate = self;
     
     _picker = [[UIPickerView alloc] initWithFrame:CGRectMake(0, self.view.height/1.5,self.view.width,self.view.height/3 )];
     //    指定Delegate
     _picker.delegate=self;
     NSArray *dataArray = [[NSArray alloc]initWithObjects:@"中国工商银行",@"中国农业银行",@"中国银行",@"中国建设银行",@"交通银行",@"中国建设银行",@"交通银行",@"招商银行",@"兴业银行",@"中国民生银行",@"广东发展银行",@"深圳发展银行",@"上海浦东发展银行",@"华夏银行",@"富滇银行",@"中国光大银行",@"中信银行",@"平安银行",@"东亚银行",@"上海银行",@"中国邮政银行",@"南京银行",@"上海农商银行",@"渤海银行",@"成都银行",@"北京银行",nil];
     _pickdata=dataArray;
     _picker.showsSelectionIndicator=YES;
     _banktext.inputView = self.picker;
     _banktext.inputAccessoryView = self.toolBar;
     
     _addresspicker =[[UIPickerView alloc] initWithFrame:CGRectMake(0, self.view.height/1.5,self.view.width,self.view.height/3 )];
     _addresspicker.delegate = self;
     self.selectaddressView = [[AddressView alloc] init];
     self.provincetext.inputView = self.selectaddressView;
     self.provincetext.inputAccessoryView = self.addresstoolBar;
}

- (UIToolbar *)addresstoolBar{
    if (_addresstoolBar == nil) {
        self.addresstoolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 44)];
        _addresstoolBar.barTintColor= CYColor(95, 200, 100, 1);
        UIBarButtonItem *item1=[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
        UIBarButtonItem *item2=[[UIBarButtonItem alloc]initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(bankclick)];
        _addresstoolBar.items = @[item1, item2];
    }
    return _addresstoolBar;
}

- (void)bankclick {
    if (_provincetext.isFirstResponder) {
        [_provincetext resignFirstResponder];
        self.provincetext.text = [NSString stringWithFormat:@"%@%@%@",self.selectaddressView.province,self.selectaddressView.city,self.selectaddressView.area];
        _provincestr = self.selectaddressView.province;
        _citystr = self.selectaddressView.city;
        _areastr = self.selectaddressView.area;
        
        //            NSLog(@"text = %@",_areaText);
    }
    if([_provincetext.text  isEqual: @"(null)(null)(null)"]) {
        _provincestr = @"北京市";
        _citystr = @"北京辖区";
        _areastr = @"东城区";
        _provincetext.text = [NSString stringWithFormat:@"%@%@%@",_provincestr,_citystr,_areastr];
    }
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    //主要是[receiver resignFirstResponder]在哪调用就能把receiver对应的键盘往下收
    [_cardtext resignFirstResponder];
    [_fenhangtext resignFirstResponder];
     [_banktext resignFirstResponder];
     [_provincetext resignFirstResponder];
    return YES;
}

//返回显示的列数
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}
//返回当前列显示的行数
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return [_pickdata count];
}

#pragma mark Picker Delegate Methods

//返回当前行的内容,此处是将数组中数值添加到滚动的那个显示栏上
-(NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    return [_pickdata objectAtIndex:row];
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    _banktext.text = _pickdata[row];
    
}
- (UIToolbar *)toolBar{
    if (_toolBar == nil) {
        self.toolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 44)];
        _toolBar.barTintColor= CYColor(103, 190, 102, 1);
        
        UIBarButtonItem *item1=[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
//        UIBarButtonItem *item2=[[UIBarButtonItem alloc]initWithTitle:@"请选择银行" style:UIBarButtonItemStylePlain target:self action:nil];
        UIBarButtonItem *item2 = [[UIBarButtonItem alloc]initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(confirm)];
        _toolBar.items = @[item1, item2];
    }
    return _toolBar;
}
- (void)confirm {
    if ([_banktext.text isEqualToString:@""]) {
        self.banktext.text = @"中国工商银行";
    }
    [self.banktext resignFirstResponder];
}

- (BOOL)checkSuccess {
    if (!_banktext||!_banktext.text.length||!_provincetext||!_provincetext.text.length||!_cardtext||!_cardtext.text.length) {
        CYAlertView(@"请填写全信息");
        return NO;
    }
    return YES;
}


- (void)click{
     BOOL  a = [CYTool IsBankCard:_cardtext.text];
     if (!a) {
          //满足
          CYAlertView(@"请输入正确的银行卡号");
          return;

     }
     
    if ([self checkSuccess]) {
         UIAlertView *txaler = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"1.如需快速提现到账，请务必准确填写开户行名称;2.所有的余额提现都只会打到绑定的银行卡里面;3.银行卡信息填写错误，将导致转账失败，请仔细审核。" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
         [txaler show];
         [txaler showAlertViewWithCompleteBlock:^(NSInteger buttonIndex) {
              if (buttonIndex == 1) {
                   DCPaymentView *payAlert = [[DCPaymentView alloc]init];
                   payAlert.detail = @"请输入交易密码";
                   [payAlert show];
                   payAlert.completeHandle = ^(NSString *inputPwd) {
                        NSString *desstr = [CYDES3Util encrypt:inputPwd];
                        CYUser *user = [CYLoginHttpTool userData].user;
                        if (!_fenhangtext.text||!_fenhangtext.text.length) {
                             _fenhangtext.text = @"";
                        }
                        CYLog(@"pro=%@,city=%@,area=%@",_provincestr,_citystr,_areastr);
                        [MBProgressHUD showMessage:nil toView:self.view];
                        [CYHttpTool postWithURL:[CYURL shared].bandCard params:@{@"userId":user.userId,@"token":user.token,@"cardType":_banktext.text,@"bankName":@"",@"province":_provincestr,@"city":_citystr,@"cardNo":_cardtext.text,@"saleNetwork":_fenhangtext.text,@"dealCode":desstr} success:^(id json) {
                             [MBProgressHUD hideHUDForView:self.view];
                             CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
                             if (jsonInfo.isSuccess) {
                                  user.name = _namestr;
                                  user.certificateNo = _idcardstr;
                                  CYAlertView(jsonInfo.message);
                                  //将最新的用户信息保存到沙盒
                                  [CYLoginHttpTool updateUserData:user];
                                  [self.navigationController popViewControllerAnimated:YES];
                                  [self.navigationController popViewControllerAnimated:YES];
                                  [CYJumpsTool jumpToMain:self.view];
                                  
                             }else{
                                  
                                  CYAlertView(jsonInfo.message);
                             }

                        } failure:^(NSError *error) {
                             [MBProgressHUD hideHUDForView:self.view];
                             CYLog(@"ERROR = %@",error);
                        }];
                        
                   };

                   
              }
              
         }];
        
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [DSNavigationBar setNavigationBarWithNavigationBar:self.navigationController.navigationBar color:CYColor(99, 207, 106, 1)];
}

- (void)viewWillDisappear:(BOOL)animated {
     [super viewWillDisappear:animated];
     [_writeView removeFromSuperview];
     [_shituview removeFromSuperview];
}
#pragma mark - Table view data source

/*
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:<#@"reuseIdentifier"#> forIndexPath:indexPath];
    
    // Configure the cell...
    
    return cell;
}
*/

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
